package ltd.followkba.comment;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import ltd.advskin.MRAM;
import ltd.advskin.utils.SubUtils;
import ltd.advskin.utils.SysUtils;
import ltd.followkba.comment.bean.BCommInfo;
import ltd.followkba.comment.bean.BOldRankInfo;
import ltd.followkba.comment.bean.BSongInfo;
import ltd.followkba.comment.bean.BUserInfo;
import ltd.followkba.comment.utils.CodeBase64;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;

import static ltd.followkba.comment.MKCC.APPC_ADD_CARE;
import static ltd.followkba.comment.MKCC.APPC_CHECK_LOGIN;
import static ltd.followkba.comment.MKCC.APPC_GET_AUTH_CODE;
import static ltd.followkba.comment.MKCC.APPC_GET_COMMENT_LIST;
import static ltd.followkba.comment.MKCC.APPC_GET_COMMENT_USERID;
import static ltd.followkba.comment.MKCC.APPC_GET_RANK_LIST;
import static ltd.followkba.comment.MKCC.APPC_GET_SONG_INFO;
import static ltd.followkba.comment.MKCC.APPC_GET_SONG_LIST;
import static ltd.followkba.comment.MKCC.APPC_GET_USER_INFO;
import static ltd.followkba.comment.MKCC.APPC_MODIFY_ACCOUNTID;
import static ltd.followkba.comment.MKCC.APPC_MODIFY_ME;
import static ltd.followkba.comment.MKCC.APPC_PUT_COMMENT;
import static ltd.followkba.comment.MKCC.APPC_PUT_FLOWER;
import static ltd.followkba.comment.MKCC.APPC_SEARCH_USER;
import static ltd.followkba.comment.MKCC.APPC_USER_LOGIN;
import static ltd.followkba.comment.MKCC.APPC_WEIBO_AUTH;
import static ltd.followkba.comment.MKCC.APPC_WEIBO_REGISTER;
import static ltd.followkba.comment.MKCC.cKCB_SW_CHANGBA;
import static ltd.advskin.MSKIN.MLOGE;

/**
 * Created by Administrator on 2016/9/30.
 */

public class KgChangBa extends KgAppBase {
    public KgChangBa(){
        SwitchAppType(cKCB_SW_CHANGBA);
     }

    @Override
    public void SwitchUser(String mixAccount, String longitude, String latitude){       // USERID,TOKE
        String[] params = mixAccount.split(",");
        gsUserID = "";
        gsToken = "";
        if (params.length > 1) {
            gsUserID = params[0];
            gsToken = "T" + params[1];
//MSTRING("SwitchUser "+ gsUserID +" "+gsToken);
        }
        gsMixAccount = mixAccount;
        if ("".equals(longitude) || "".equals(latitude)){
            SetLongitudeLatitude(0);
        }
        else {
            gsLatitude = latitude;
            gsLongitude = longitude;
        }
        String gsLocal_1 = MUTIL.GET_MD5_STRING(gsUserID);
        gsLocal_1 = gsLocal_1.toUpperCase();
        StringBuffer stringBuffer = new StringBuffer(gsLocal_1);
        int g4Local_1 = 2;
        do {
            stringBuffer.insert(g4Local_1, "%3A");
            g4Local_1 += 3+2;
        } while (g4Local_1 < 27);
        mDeviceMac = stringBuffer.toString().substring(0, 27);
        mDeviceMac = mDeviceMac.toUpperCase();
        gsLocal_1 = "";
        if (gsLatitude.length() > 2) {
            gsLocal_1 = gsLatitude.substring(0, 2) + gsLongitude.substring(0, 2);
        }else{
            Log.e("MSYS", "KgChangBa gsLatitude");
        }
        mUserAgent = MUTIL.GET_MOBIL_BRAND(MAPI.STRING_DEC32(gsLocal_1));
        mUserAgent = mUserAgent.substring(0, 2).toUpperCase() + "-" + gsLocal_1;
        mUserAgent = "Dalvik/1.6.0 (Linux; U; Android 4.3; " + mUserAgent + " Build/JSS15J)";
//MSTRING("SwitchUser " + gsMac +" "+gsUserID + " "+gsUserAgent + " "+gsLatitude + " "+gsLongitude);
    }
    @Override
    public String CheckLogin(){
        ResultNet resultNet = WriteCommand(APPC_CHECK_LOGIN, "", "");
//MSTRING(resultNet);
        if (resultNet.sucess) {
//MSTRING("CheckLogin "+MUTIL.GET_JSON_STRING(resultNet.nextJason, "valid_city")+" "+MUTIL.GET_JSON_STRING(resultNet.nextJason, "wochangbadesc"));
            return "ok";
        }
        return resultNet.message;
    }
    @Override
    public String LoginSvr(String account, String password, String authCode){
        ResultNet resultNet = WriteCommand(APPC_USER_LOGIN, account, password, authCode);
        if (resultNet.sucess){
            return "ok";
        }
        return resultNet.message;
    }
    @Override
    public BUserInfo GetUserFullInfo(String mixAccount, BUserInfo beforeUserInfo){
        if ("".equals(mixAccount)){
            mixAccount = gsUserID;
        }
        else {
            int g4Local_1 = mixAccount.indexOf("#");
            if (g4Local_1 > 0) {
                mixAccount = mixAccount.substring(0, g4Local_1);
            }
            g4Local_1 = mixAccount.indexOf(",");
            if (g4Local_1 > 0) {
                mixAccount = mixAccount.substring(0, g4Local_1);
            }
        }
        BUserInfo bUserInfo = null;
        ResultNet resultNet;
        int beforeCounter = 0;
//MSTRING("唱吧GetUserFullInfo A" + mixAccount);
        if (beforeUserInfo == null) {
            resultNet = WriteCommand(APPC_GET_USER_INFO, mixAccount, "");
MSTRING("唱吧GetUserFullInfo " + mixAccount + resultNet.message);
            if (resultNet.sucess && resultNet.result.size() > 0) {
                bUserInfo = (BUserInfo) resultNet.result.get(0);
            }
        }
        else {
            bUserInfo = beforeUserInfo;
            if (bUserInfo.songIDs != null) {
                beforeCounter = bUserInfo.songIDs.size();
//                MSTRING("GetUserFullInfo A "+beforeCounter);
            }
        }
        if (bUserInfo != null) {
            if (beforeCounter >= bUserInfo.songQty){        // 所有歌曲列表已经读取
                bUserInfo.beforeTime = "end";
                return bUserInfo;
            }
            resultNet = WriteCommand(APPC_GET_SONG_LIST, mixAccount, String.format("%d", beforeCounter));
            if (resultNet.result != null && resultNet.result.size() > 0) {
//MSTRING("KgChangBa GetUserFullInfo B "+beforeCounter+" "+bUserInfo.UserIdS+" "+bUserInfo.IdS);
                if (bUserInfo.songIDs == null) {
                    bUserInfo.songIDs = new ArrayList<>();
                }
                bUserInfo.songIDs.addAll(resultNet.result);
//MSTRING("GetUserFullInfo "+BUserInfo.UserIdS+" "+BUserInfo.UserName+" "+BUserInfo.IdS.size());
            }
            if (bUserInfo.songIDs != null && bUserInfo.newSong == null) {
                bUserInfo.newSong = GetSongInfo(bUserInfo.songIDs.get(0));
//            MSTRING("GetUserFullInfo C "+bUserInfo.NewWorks+" "+bUserInfo.IdS.get(0));
            }
            return bUserInfo;
        }
        return null;
    }
    @Override
    public ResultNet GetRankList(){
        SetLongitudeLatitude(0);
        String city = MUTIL.GET_RANK_CHNAG_BA(mRankCounter);
        ResultNet resultNet = WriteCommand(APPC_GET_RANK_LIST, city, "");
        resultNet.message = city;
        return resultNet;
    }
    @Override
    public ResultNet GetCommentList(int counter, String userID, String SongID, String commentID){
        if (counter == -1) {
            return WriteCommand(APPC_GET_COMMENT_USERID, commentID, "");
        }
        return WriteCommand(APPC_GET_COMMENT_LIST, commentID, "");
    }
    @Override
    public String PutCommentToSong(String userID, String songID, String commentID, String comment){
        ResultNet resultNet = WriteCommand(APPC_PUT_COMMENT, userID, songID, comment);
        if (resultNet.sucess){
            return "ok";
        }
        return resultNet.message;
    }
    @Override
    public String AddCareUser(String userID){
        ResultNet resultNet = WriteCommand(APPC_ADD_CARE, userID, "");
        if (resultNet.sucess){
            return "ok";
        }
        return resultNet.message;
    }
    @Override
    public String PutFlowerToSong(String songID){
        ResultNet resultNet = WriteCommand(APPC_PUT_FLOWER, songID, "", "");
        if (resultNet.sucess){
            return resultNet.message;
        }
        return "0";
    }

    @Override
    public String ModifyUseInfo(int retry, BUserInfo BUserInfo) {
        // String Gender, String UserName, String Intro, String Province, String City, String Birthday
//        Intro="冰凌花开在山崖，迎风冒雪都不怕，寒冷中发芽……";
        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        ResultNet resultNet = null;
        int g4Local_1 = 0;
        do{
            gsLocal_1 = "";
            if (g4Local_1 == 0) {
                gsLocal_1 = "&Gender=" + BUserInfo.gender;
            }
            gsLocal_1 += "&Birthday=" + BUserInfo.birthday;
            gsLocal_1 += "&location=" + URLEncoder.encode(BUserInfo.province + " " + BUserInfo.city);
            gsLocal_2 = BUserInfo.nickName;
            if (g4Local_1 > 0) {
                if (resultNet.message.indexOf("艺名已经被占用") >= 0) {           // 哎呀！这个艺名已经被占用了，换一个试试吧
                    if (g4Local_1 < 2) {                       // 第一次
                        gsLocal_2 = BUserInfo.nickName + MUTIL.GET_RANDOM_NUMBER(3);
                    } else {
                        gsLocal_2 = MUTIL.GET_RANDOM_PASSWORD();
                    }
                }
            }
            gsLocal_1 += "&nickname=" + URLEncoder.encode(gsLocal_2);
            gsLocal_3 = BUserInfo.intro;
            if (g4Local_1 > 0) {
                if (resultNet.message.indexOf("签名中") >= 0){                 // 你的签名中包含敏感词，请重新修改
                    if (g4Local_1 == 1) {                       // 第一次
                        gsLocal_3 = BUserInfo.intro.substring(0, BUserInfo.intro.length()/2) + MUTIL.GET_RANDOM_NUMBER(5);
                    }
                    else if (g4Local_1 == 2) {                       // 第二次
                        gsLocal_3 = BUserInfo.intro.substring(BUserInfo.intro.length()/2, BUserInfo.intro.length()) + MUTIL.GET_RANDOM_NUMBER(5);
                    }
                    else if (g4Local_1 == 3) {
                        gsLocal_3 = BUserInfo.nickName;
                    }
                    else {
                        gsLocal_3 = MUTIL.GET_RANDOM_PASSWORD();
                    }
                }
            }
            gsLocal_1 += "&signature=" + URLEncoder.encode(gsLocal_3);
            resultNet = WriteCommand(APPC_MODIFY_ME, gsLocal_1, "");
            if (resultNet.sucess){
                return "ok";
            }
            else {
MSTRING(String.format("%d修改自己出错 %s %s %s",g4Local_1,gsLocal_2, gsLocal_3, resultNet.message));
            }
            if (resultNet.message.indexOf("不能再变更") >= 0) {             // 性别已经修改过一次，不能再变更
            }
        } while(++g4Local_1 < retry);
        return resultNet.message;
    }
    @Override
    public BSongInfo GetSongInfo(String SongID){
        if (!"".equals(SongID)) {
            ResultNet resultNet = WriteCommand(APPC_GET_SONG_INFO, SongID, "");
            if (resultNet.sucess && resultNet.result.size() > 0) {
                return (BSongInfo)resultNet.result.get(0);
            }
        }
        return null;
    }
    @Override
    public String GetAuthCode() {
        WriteCommand(APPC_GET_AUTH_CODE, "", "");
        return gsWorkPath + "AuthCode.png";
    }
    @Override
    public List<String> SearchUser(int type, String user) {
        if (type == 0){
            ResultNet resultNet = WriteCommand(APPC_SEARCH_USER, user, "");
            if (resultNet.sucess){
                return resultNet.result;
            }
        }
        else {                                                  // 查找链接
        }
        return null;
    }
    @Override
    public String downloadHeadFile(BUserInfo bUserInfo) {
        bUserInfo.headFile = String.format("%s%d_%s.jpg", MKCS.gsPhotoPath, AppType, bUserInfo.userID);
        if (MAPI.GET_FILE_LENGTH(bUserInfo.headFile) < 500) {
            String gsLocal_1 = bUserInfo.headUrl;
            if (gsLocal_1.length() > 10){
                gsLocal_1 = gsLocal_1.substring(0, gsLocal_1.length() - 4) + "_100_100" + gsLocal_1.substring(gsLocal_1.length() - 4, gsLocal_1.length());
            }
            if (MUTIL.GET_URL_TO_FILE(gsLocal_1, bUserInfo.headFile) < 500) {
                return "error HeadFile";
            }
        }
//        MSTRING("downloadHeadFile A "+MAPI.GET_FILE_LENGTH(bUserInfo.HeadFile)+" "+ bUserInfo.HeadFile);
        return "ok";
    }

    public ResultNet WriteCommand(int type, String aux1, String aux2){
        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        int g4Local_1;
        int g4Local_2;
        ResultNet resultNet = new ResultNet();
        switch (type){
            case APPC_SEARCH_USER:
                gsLocal_1 = "http://api.changba.com/ktvbox.php?curuserid=" + gsUserID + "&token=" + gsToken + "&bless=1&macaddress=" + mDeviceMac;
                gsLocal_1 += "&keyword=" + URLEncoder.encode(aux1) + "&ac=searchuserbynickname&channelsrc=changba&deviceid=" + mDeviceMac + "&version=8.6.2";
                gsLocal_2 = WriteToSvr(gsLocal_1);
MSTRING("APPC_SEARCH_USER 1 " + gsLocal_2);
                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
                    List<String> aUserLists = new ArrayList<>();
                    JSONArray jsonArray;
                    try {
                        jsonArray = new JSONArray(resultNet.nextJason);
                        g4Local_1 = jsonArray.length();
// MSTRING("APPC_SEARCH_USER 2 "+g4Local_1);
                        g4Local_2 = 0;
                        while (g4Local_2 < g4Local_1) {
                            JSONObject jsonObj = jsonArray.getJSONObject(g4Local_2);
                            gsLocal_2 = jsonObj.getString("userid");
//MSTRING("APPC_SEARCH_USER 5"+gsLocal_2);
                            aUserLists.add(gsLocal_2);
                            ++g4Local_2;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    resultNet.result = aUserLists;
                }
                break;
            case APPC_CHECK_LOGIN:
                gsLocal_1 = "http://api.changba.com/ktvbox.php?&curuserid=" + gsUserID + "&specialurl=uni&token=" + gsToken + "&bless=1&macaddress=" + mDeviceMac;
                gsLocal_1 += "&ac=getwochangbastatus&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";
                gsLocal_2 = WriteToSvr(gsLocal_1);                  // 联通沃
//MSTRING("APPC_CHECK_LOGIN "+gsUserID + " " + gsToken+" "+gsLocal_2);
                MakeStdReturn(gsLocal_2, resultNet);
                break;
            case APPC_GET_USER_INFO :
                List<BUserInfo> BUserInfos = new ArrayList<>();
                BUserInfo BUserInfo = new BUserInfo();
                gsLocal_1 = "http://api.changba.com/ktvbox.php?&bless=1&macaddress=" + mDeviceMac + "&userid=" + aux1;
                gsLocal_1 += "&ac=getuserinfo&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";
                //gsLocal_1 = WriteToSvr(CreateAcString("getuserinfo", aux1, ""));
                gsLocal_2 = WriteToSvr(gsLocal_1);
//MSTRING("GET_USER_INFO "+gsLocal_1+" " + gsLocal_2);
                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
                    BUserInfo.userID = aux1;
                    BUserInfo.nickName = MUTIL.GET_JSON_STRING(resultNet.nextJason, "nickname");
                    BUserInfo.ChangBaID = MUTIL.GET_JSON_STRING(resultNet.nextJason, "accountid");
                    BUserInfo.gender = MUTIL.GET_JSON_STRING(resultNet.nextJason, "Gender");
                    BUserInfo.intro = MUTIL.GET_JSON_STRING(resultNet.nextJason, "signature");
                    BUserInfo.headUrl = MUTIL.GET_JSON_STRING(resultNet.nextJason, "headphoto");
                    BUserInfo.birthday = MUTIL.GET_JSON_STRING(resultNet.nextJason, "Birthday");
                    BUserInfo.province = MUTIL.GET_JSON_STRING(resultNet.nextJason, "Province");
                    BUserInfo.city = MUTIL.GET_JSON_STRING(resultNet.nextJason, "City");
                    BUserInfo.longitude = MUTIL.GET_JSON_STRING(resultNet.nextJason, "longitude");
                    BUserInfo.latitude = MUTIL.GET_JSON_STRING(resultNet.nextJason, "latitude");
//
//                    BUserInfo.FansQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "fansnum");
//                    BUserInfo.CareQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "friendsnum");
//MSTRING("FansQty "+BUserInfo.FansQty+" "+BUserInfo.CareQty);
                }
//                gsLocal_1 = "http://api.changba.com/ktvbox.php?curuserid=" + gsUserID + "&token=Taf2e516861ecfe4&bless=1&macaddress=";
//                gsLocal_1 += gsMac + "&userid=" + aux1 + "&&ac=getuserrelationnum&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + "&version=8.6.2";
//                gsLocal_2 = WriteToSvr(gsLocal_1);
                gsLocal_2 = WriteToSvr(CreateAcString("getuserrelationnum", aux1, ""));
//MSTRING("getuserrelationnum "+gsLocal_2);
                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
                    BUserInfo.fansQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "fansnum");
//                    BUserInfo.CareQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "friendsnum");
//MSTRING("CareQty "+BUserInfo.FansQty+" "+BUserInfo.CareQty);
//
//                    gsLocal_2 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "user_events");
////MDWORD(0x9a);MSTRING(gsLocal_1);MSTRING(gsLocal_2);
//                    BUserInfo.NewNoticeQty = MUTIL.GET_JSON_STRING(gsLocal_2, "newnotice_num");

//MSTRING(BUserInfo.NewNoticeQty);
                }
                gsLocal_2 = WriteToSvr(CreateAcString("getuserstatistics", aux1, ""));
//MDWORD(0xaa);MSTRING(gsLocal_1);
                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
                    BUserInfo.songQty = MAPI.STRING_DEC32(MUTIL.GET_JSON_STRING(resultNet.nextJason, "worknum"));
                    BUserInfo.listenQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "listennum");
                }
//MSTRING("唱吧用户：" + BUserInfo.UserName +" "+ BUserInfo.WorksQty +" "+ BUserInfo.Intro +" "+ BUserInfo.Province +" "+ BUserInfo.City +" "+ BUserInfo.HeadUrl);
                BUserInfos.add(BUserInfo);
                resultNet.result = BUserInfos;
                break;
            case APPC_GET_SONG_INFO :
                gsLocal_1 = "http://api.changba.com/ktvbox.php?ac=getuserwork&curuserid=" + gsUserID + "&token=" + gsToken + "&clksrc=userworklist&workid=";
                gsLocal_1 += aux1 + "&bless=1&macaddress=" + mDeviceMac + "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";
                gsLocal_2 = WriteToSvr(gsLocal_1);
//MSTRING("APPC_GET_SONG_INFO "+aux1+" "+gsLocal_2);
                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
                    List<BSongInfo> bSongInfos = new ArrayList<>();
                    BSongInfo bSongInfo = new BSongInfo();
//MSTRING(resultNet.nextJason);
                    bSongInfo.songID = MUTIL.GET_JSON_STRING(resultNet.nextJason, "workid");
                    bSongInfo.intro = MUTIL.GET_JSON_STRING(resultNet.nextJason, "title");
                    bSongInfo.path = MUTIL.GET_JSON_STRING(resultNet.nextJason, "workpath");
                    bSongInfo.commentQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "comment_num");
                    bSongInfo.listenQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "listen_num");
                    bSongInfo.flowerQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "flower_num");
                    bSongInfo.shareQty = MUTIL.GET_JSON_STRING(resultNet.nextJason, "forward_num");
                    bSongInfo.createTime = MUTIL.GET_JSON_STRING(resultNet.nextJason, "addtime");
                    bSongInfo.createTime = MUTIL.CHANG_DATE_FORMAT(bSongInfo.createTime);
                    gsLocal_3 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "song");
                    bSongInfo.musicID = MUTIL.GET_JSON_STRING(gsLocal_3, "songid");
                    bSongInfo.songName = MUTIL.GET_JSON_STRING(gsLocal_3, "name");
//MSTRING(aSongInfo.MusicIdS + " ddd " +aSongInfo.WorksName);
                    gsLocal_3 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "video");
                    bSongInfo.isMV = "0";
//MSTRING(gsLocal_3);
                    if (!"".equals(gsLocal_3)) {
                        bSongInfo.videoPath = MUTIL.GET_JSON_STRING(gsLocal_3, "videourl");
                        if ("".equals(bSongInfo.videoPath)) {
                            try {
                                gsLocal_2 = MUTIL.GET_JSON_STRING(gsLocal_3, "videourl_altlist");
                                JSONArray videoAlt = null;
                                videoAlt = new JSONArray(gsLocal_2);
                                if (videoAlt.length() > 0){
                                    bSongInfo.videoPath = videoAlt.getString(0);
                                    if ("".equals(bSongInfo.videoPath) && videoAlt.length() > 1){
                                        bSongInfo.videoPath = videoAlt.getString(1);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        if (!"".equals(bSongInfo.videoPath)) {
//MSTRING(aSongInfo.VideoUrl);
                            bSongInfo.isMV = "1";
                        }
                    }

                    bSongInfos.add(bSongInfo);
                    resultNet.result = bSongInfos;
                }
//MSTRING("SONG_INFO"+resultNet.message);
                break;
            case APPC_GET_SONG_LIST:
                gsLocal_1 = WriteToSvr(CreateAcString("getmixeduserworklist", aux1, aux2));
                MAPI.WRITE_BUFF8_FILE(false, gsLocal_1.getBytes().length, 0, gsLocal_1.getBytes(), MRAM.gsRootPath+"aa.txt");
//MSTRING(gsLocal_1);
                if (MakeStdReturn(gsLocal_1, resultNet)) {
                    List<String> aSongLists = new ArrayList<>();
                    //gsLocal_2 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "feeds");
//MSTRING("APPC_GET_SONG_LIST A：" + aux1 +" "+aux2 +" "+gsLocal_1);
//MLOG(resultNet.nextJason);
                    JSONArray jsonArray;
                    try {
                        jsonArray = new JSONArray(resultNet.nextJason);
                        g4Local_1 = jsonArray.length();
//MLOG("APPC_GET_SONG_LIST 2 "+g4Local_1+" "+resultNet.nextJason);

                        for (int counter = 0; counter < g4Local_1; counter++) {
//                            gsLocal_2 = "0";
                            try {
                                JSONObject jsonObj = jsonArray.getJSONObject(counter);
                                gsLocal_3 = jsonObj.getString("type");
                                if ("0".equals(gsLocal_3)) {
                                    gsLocal_2 = jsonObj.getString("work");
                                    gsLocal_2 = MUTIL.GET_JSON_STRING(gsLocal_2, "workid");
                                    aSongLists.add(gsLocal_2);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
//                                MSTRING("APPC_GET_SONG_LIST 444 ");
                            }
//                            MSTRING("APPC_GET_SONG_LIST B "+counter+" "+gsLocal_2);

                        }
//MSTRING("APPC_GET_SONG_LIST C "+g4Local_1+" "+aSongLists.size());
                    } catch (JSONException e) {
                        e.printStackTrace();
//MSTRING("APPC_GET_SONG_LIST 444 ");
                    }
                    resultNet.result = aSongLists;
                }
                break;
            case APPC_GET_COMMENT_LIST :
            case APPC_GET_COMMENT_USERID:
                gsLocal_1 = "http://api.changba.com/ktvbox.php?num=20&workid=" + aux1 + "&start=" + aux2;
                gsLocal_1 += "&workowner=49860567&smiley=1&bless=1&macaddress=" + mDeviceMac;
                gsLocal_1 += "&ac=getworkcomment2&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";
                gsLocal_2 = WriteToSvr(gsLocal_1);
//MLOG("APPC_GET_COMMENT_LIST " + gsLocal_2);
                if (MakeStdReturn(gsLocal_2, resultNet) == true) {

                    try {
                        gsLocal_3 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "comments");
                        JSONArray jsonArray = new JSONArray(gsLocal_3);
                        g4Local_1 = jsonArray.length();
//MLOG("comments " + g4Local_1);
                        int g4Local_3;
                        int g4Local_4;
                        g4Local_2 = 0;
                        if (type == APPC_GET_COMMENT_USERID){
                            List<String> commLists = new ArrayList<>();
                            JSONObject jsonobject;
                            while (g4Local_2 < g4Local_1) {
                                jsonobject = jsonArray.getJSONObject(g4Local_2);
                                gsLocal_2 = jsonobject.getString("user");
                                commLists.add(MUTIL.GET_JSON_STRING(gsLocal_2, "userid"));
                                ++g4Local_2;
                            }
                            resultNet.result = commLists;
                        }
                        else {
                            List<BCommInfo> commLists = new ArrayList<>();
                            while (g4Local_2 < g4Local_1) {
                                BCommInfo bCommInfo = MakeACommInfo(jsonArray, g4Local_2);
                                g4Local_3 = MAPI.STRING_DEC32(bCommInfo.totalReply);
//MLOG(bCommInfo.BUserInfo.HeadUrl);MLOG(bCommInfo.BUserInfo.UserIdS);
                                if (g4Local_3 > 0) {
                                }
                                commLists.add(bCommInfo);
                                ++g4Local_2;
                            }
                            resultNet.result = commLists;
                        }
                        MSTRING(String.format("唱吧评论：%d/%d条(%dB)", g4Local_2, g4Local_1, gsLocal_1.length()));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
               }
                break;
            case APPC_GET_RANK_LIST :
                gsLocal_1 = "http://vapi.changba.com/ktvbox_apiproxy.php?ac=gethottestwork&num=96&area=";
                if (!"全国".equals(aux1)){
                    gsLocal_1 += URLEncoder.encode(aux1);
                }
                gsLocal_1 += "&start=0&bless=1&channelsrc=market_%E8%85%BE%E8%AE%AF&macaddress=88%3A32%3A9B%3AC2%3A68%3AAD&deviceid=88%3A32%3A9B%3AC2%3A68%3AAD&version=8.6.2";
                gsLocal_2 = WriteToSvr(gsLocal_1);
                MSTRING("APPC_READ_RANK A " + aux1 +" "+gsLocal_2);
                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
                    List<BOldRankInfo> topLists = new ArrayList<>();
                    try {
                        JSONArray jsonArray = new JSONArray(resultNet.nextJason);
                        g4Local_1 = jsonArray.length();
                        g4Local_2 = 0;
                        while (g4Local_2 < g4Local_1) {
                            JSONObject jsonobject = jsonArray.getJSONObject(g4Local_2);
                            BOldRankInfo bOldRankInfo = new BOldRankInfo();
                            bOldRankInfo.SongID = jsonobject.getString("workid");
//                            bOldRankInfo.UserIntro = jsonobject.getString("title");

                            gsLocal_2 = jsonobject.getString("user");
                            bOldRankInfo.UserID = MUTIL.GET_JSON_STRING(gsLocal_2, "userid");
                            bOldRankInfo.NickName = MUTIL.GET_JSON_STRING(gsLocal_2, "nickname");
                            gsLocal_2 = jsonobject.getString("song");
                            bOldRankInfo.SongName = MUTIL.GET_JSON_STRING(gsLocal_2, "name");
//MLOG("APPC_READ_RANK B " + bOldRankInfo.WorksName);
                            topLists.add(bOldRankInfo);
//MLOG(MUTIL.GET_JSON_STRING(gsLocal_3, "userid"));
                            ++g4Local_2;
                        } ;
                        resultNet.result = topLists;
                        MSTRING(String.format("找到唱吧%s榜用户%d个", aux1, g4Local_2));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case APPC_MODIFY_ME:
                gsLocal_1 = WriteToSvr(CreateAcString("setuserinfo", aux1, ""));
                MakeStdReturn(gsLocal_1, resultNet);
//MLOG("ME "+aux1);
//MLOG("APPC_MODIFY_ME "+gsLocal_1);
                break;
            case APPC_GET_AUTH_CODE:
                gsAuthSsid = GetOrgSsidFile(1);
                break;
            case APPC_ADD_CARE:
                gsLocal_1 = "http://api.changba.com/ktvbox.php?curuserid=" + gsUserID;
                gsLocal_1 += "&token=" + gsToken + "&bless=1&macaddress=" + mDeviceMac + "&ac=followuser&follow=" + aux1;
                gsLocal_1 += "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";

                gsLocal_3 = WriteToSvr(gsLocal_1);
                MakeStdReturn(gsLocal_3, resultNet);
                MSTRING("APPC_ADD_CARE " +gsUserID+" "+ gsLocal_1+" "+ gsLocal_3 +" "+resultNet.message);
                break;
        }
        return resultNet;
    }
    public BCommInfo MakeACommInfo(JSONArray jsonArray, int counter){
        BCommInfo bCommInfo = new BCommInfo();
        try {
            JSONObject jsonobject = jsonArray.getJSONObject(counter);
            bCommInfo.aUserInfo = new BUserInfo();
            String gsLocal_2 = jsonobject.getString("user");
            bCommInfo.aUserInfo.userID = MUTIL.GET_JSON_STRING(gsLocal_2, "userid");
            bCommInfo.aUserInfo.nickName = MUTIL.GET_JSON_STRING(gsLocal_2, "nickname");
            bCommInfo.aUserInfo.headUrl = MUTIL.GET_JSON_STRING(gsLocal_2, "headphoto");
            bCommInfo.aUserInfo.gender = MUTIL.GET_JSON_STRING(gsLocal_2, "Gender");
//MLOG("content1 " + bCommInfo.BUserInfo.UserName);
//MLOG("content2 " + bCommInfo.BUserInfo.HeadUrl);
            bCommInfo.commentID = jsonobject.getString("commentid");
            bCommInfo.content = jsonobject.getString("content");
            bCommInfo.createTime = MUTIL.CHANG_DATE_FORMAT(jsonobject.getString("time"));
            bCommInfo.totalReply = jsonobject.getString("replynum");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return bCommInfo;
    }
    public ResultNet WriteCommand(int type, String aux1, String aux2, String aux3){
        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        ResultNet resultNet = new ResultNet();
        switch (type) {
            case APPC_USER_LOGIN:
                gsLocal_1 = MUTIL.GET_MD5_STRING(gsAuthSsid + "ba!se");
                gsLocal_2 = gsLocal_1.substring(0, 10);
                gsLocal_1 = MUTIL.GET_MD5_STRING(aux2);
                if (aux3.startsWith("c2")){
                    gsLocal_3 = "";
                }
                else {
                    gsLocal_3 = URLEncoder.encode(aux3);
                }
                gsLocal_1 = "https://secure.changba.com/ktvboxs.php?ac=llogin&md5pwd=" + gsLocal_1 + "&email="+aux1+"&ssid="+gsLocal_2+"&captcha=" + gsLocal_3;
                gsLocal_1 += "&channelsrc=changba&deviceid="+mDeviceMac+"&bless=1&macaddress="+mDeviceMac+"&version=8.6.2";
                gsLocal_3 = httpsConnectionGet(gsLocal_1);
                if (MakeStdReturn(gsLocal_3, resultNet)){
MSTRING("KgChangBa APPC_USER_LOGIN "+resultNet.message+"_ "+gsLocal_3);
                    gsUserID = MUTIL.GET_JSON_STRING(resultNet.nextJason, "userid");
                    gsToken = MUTIL.GET_JSON_STRING(resultNet.nextJason, "token");
                    if (!"".equals(gsUserID) && !"".equals(gsToken)){
                        gsMixAccount = gsUserID + "," + gsToken.substring(1, gsToken.length());
MSTRING("KgChangBa LoginFlag "+gsMixAccount+" "+gsToken);
                    }
                }
                break;
            case APPC_WEIBO_AUTH:
                if ("".equals(aux2)) {
                    aux2 = GetInsideSsid();
                    aux3 = "";
                }
                gsLocal_2 = "https://secure.changba.com/ktvboxs.php?ac=ssoentry&sso_code="+aux1+"&sso_type=sina&ssid="+aux2+"&captcha=" + URLEncoder.encode(aux3);
                gsLocal_2 += "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid="+mDeviceMac+"&bless=1&macaddress="+mDeviceMac+"&version=8.6.2";
                gsLocal_3 = httpsConnectionGet(gsLocal_2);
                MakeStdReturn(gsLocal_3, resultNet);
                MSTRING("APPC_WEIBO_AUTH "+aux2+"_"+aux3+"_"+resultNet.message+"_ "+gsLocal_3);
                break;
            case APPC_WEIBO_REGISTER:
                gsLocal_1 = "https://secure.changba.com/ktvboxs.php?ac=changbaregister&sso_code="+aux1+"&Gender="+aux3+"&sso_openid="+aux2+"&sso_type=sina&nickname=";
                gsLocal_1 += MUTIL.GET_RANDOM_PASSWORD() + "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid="+mDeviceMac+"&bless=1&macaddress="+mDeviceMac+"&version=8.6.2";
                gsLocal_3 = httpsConnectionGet(gsLocal_1);
                MakeStdReturn(gsLocal_3, resultNet);
                MSTRING("APPC_WEIBO_REGISTER "+gsLocal_3+" "+resultNet.message);
                break;
            case APPC_MODIFY_ACCOUNTID:
                gsLocal_2 = "https://secure.changba.com/ktvboxs.php?ac=iinituseraccountid&token="+gsToken+"&curuserid="+gsUserID+"&password=" + MUTIL.GET_MD5_STRING(aux2) + "&accountid=";
                gsLocal_2 += aux1 + "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid="+mDeviceMac+"&bless=1&macaddress="+mDeviceMac+"&version=8.6.2";
                gsLocal_3 = httpsConnectionGet(gsLocal_2);
                MakeStdReturn(gsLocal_3, resultNet);
                MSTRING("APPC_MODIFY_ACCOUNTID "+gsLocal_3+" "+resultNet.message);
                break;
            case APPC_PUT_FLOWER:
                if ("".equals(aux2)) {
                    aux2 = GetInsideSsid();
                    aux3 = "";
                }
                gsLocal_1 = "https://gapis.changba.com/ktvboxg.php?ac=givegift&curuserid=" + gsUserID + "&ssid=" + aux2 + "&giftid=0&workid=" + aux1 + "&giftnum=1&token=";
                gsLocal_1 += gsToken + "&captcha=" + URLEncoder.encode(aux3) + "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid=" + mDeviceMac + "&bless=1&macaddress=" + mDeviceMac + "&version=8.6.2";
                gsLocal_2 = httpsConnectionGet(gsLocal_1);
                if (MakeStdReturn(gsLocal_2, resultNet)) {
                    resultNet.message = MUTIL.GET_JSON_STRING(resultNet.nextJason, "flowerremainnum");
                }
                MSTRING("APPC_PUT_FLOWER "+gsLocal_2 +" "+resultNet.message);
                break;
            case APPC_PUT_COMMENT:
                gsLocal_1 = "http://api.changba.com/ktvbox.php?content=" + URLEncoder.encode(aux3) + "&curuserid=" + gsUserID + "&workid=" + aux2;
                gsLocal_1 += "&token=" + gsToken + "&bless=1&macaddress=" + mDeviceMac + "&ac=giveworkcomment&workowner=" + aux1;
                gsLocal_1 += "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";

                gsLocal_3 = WriteToSvr(gsLocal_1);
                MakeStdReturn(gsLocal_3, resultNet);
//MLOG("APPC_PUT_COMMENT " +gsUserID+" "+ gsLocal_1+" "+ gsLocal_3 +" "+resultNet.message);

//                gsLocal_1 = "http://api.changba.com/ktvbox.php?ac=getsong2&songid=454&bless=1&macaddress=" + gsMac + "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + "&version=8.6.2";
//                gsLocal_3 = WriteToSvr(gsLocal_1);
//MSTRING("getsong2 "+gsLocal_3);
                break;

        }
        return resultNet;
    }
    public String CreateAcString(String type, String userID, String start){
        String gsLocal_1 = "http://api.changba.com/ktvbox.php?";
        if (!"".equals(start)){
            gsLocal_1 += "num=20&start=" + start;
        }
        gsLocal_1 += "&curuserid=" + gsUserID + "&token=" + gsToken + "&bless=1&macaddress=" + mDeviceMac + "&userid=" + userID;
        return gsLocal_1 + "&ac=" + type + "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";
    }
    public boolean MakeStdReturn(String gsLocal_1, ResultNet netResult) {
        String gsLocal_2 = MUTIL.GET_JSON_STRING(gsLocal_1, "errorcode");
        if ("ok".equals(gsLocal_2)) {
            netResult.nextJason = MUTIL.GET_JSON_STRING(gsLocal_1, "result");
//MDWORD(0xb1);MLOG(netResult.nextJason);
            return true;
        }
        netResult.message =  gsLocal_2 + ":" + MUTIL.GET_JSON_STRING(gsLocal_1, "error");
        netResult.sucess = false;
        return false;
    }

    public String WriteToSvr(String destUrl) {
        String gsLocal_1 = "";
        BufferedInputStream bis = null;
        HttpURLConnection mHttpUrl=null;
        URL url = null;
        byte[] gLocal_Buffer = new byte[0x200000+1460];
        destUrl += MUTIL.GET_SERET_USER_INFO(destUrl);
        MSTRING("WriteToSvr "+destUrl);
        try {
  //          MLOG(destUrl);
//MLOG("网络3");
            url = new URL(destUrl);
            mHttpUrl = (HttpURLConnection) url.openConnection();
            mHttpUrl.setConnectTimeout(30000);
            mHttpUrl.setReadTimeout(30000);
            mHttpUrl.setRequestProperty("Cb-X-Seqid", "t=4;n=15;d=0");
            mHttpUrl.setRequestProperty("Connection", "Keep-Alive");
            mHttpUrl.setDoInput(true);
//MLOG("网络4");
            int responseCode = mHttpUrl.getResponseCode();
   //         MDWORD(0xe1);MDWORD(responseCode);
            if (responseCode >= 200 || responseCode < 300) {
                bis = new BufferedInputStream(mHttpUrl.getInputStream());
            }
            else {
                bis = new BufferedInputStream(mHttpUrl.getErrorStream());
            }
//MLOG("网络5");

            int size = 0;
            int g4Local_1 = 0;
            while ((size = bis.read(gLocal_Buffer, g4Local_1, 1460)) != -1) {
                if (size > 0){
                    g4Local_1 += size;
                    if (g4Local_1 >= 0x200000){
                        break;
                    }
                }
            }
            bis.close();
            if (g4Local_1 > 0){
                gsLocal_1 = new String(gLocal_Buffer, 0, g4Local_1, "utf-8");
            }
            mHttpUrl.disconnect();
//MLOG("网络11");
        } catch (IOException e) {
        }
//MLOG("网络12");
        return gsLocal_1;
    }
    private static String httpsConnectionGet(String urlPath){
        urlPath += MUTIL.GET_SERET_USER_INFO(urlPath);
        String re_str = "";
        try {
            URL url = new URL(urlPath);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.connect();
            StringBuilder builder = new StringBuilder();
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            while((line = reader.readLine())!=null){
                builder.append(line);
            }
            reader.close();
            connection.disconnect();
            re_str = builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return re_str;
    }
    private String GetInsideSsid(){
        String ssidInput  =  GetOrgSsidFile(0);
//System.out.println("ssid：" + ssidInput);
        return MUTIL.GET_MD5_STRING(ssidInput + "ba!se").substring(0,10);
    }



    private String GetOrgSsidFile(int mode){
        String gsLocal_1;
        try {
            if (mode == 0) {
                gsLocal_1 = "http://api.changba.com/login/check_code.php?&action=ssoentry&method=sina&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid=64%3Acc%3A2e%3A4d%3Ad9%3A94&bless=1&version=8.6.2&macaddress=64%3Acc%3A2e%3A4d%3Ad9%3A94";
            }
            else {
                gsLocal_1 = "http://api.changba.com/login/check_code.php?bless=1&channelsrc=changba&macaddress=" + mDeviceMac + "&deviceid=" + mDeviceMac + "&version=8.6.2&action=llogin&method=ktv";
            }
            URLConnection v0 = new URL(gsLocal_1).openConnection();;
            InputStream v3 = v0.getInputStream();
            ByteArrayOutputStream v4 = new ByteArrayOutputStream();
            byte bs [] = new byte[10];
            int size;
            while ((size = v3.read(bs))!=-1){
                v4.write(bs,0,size);
            }
            byte[] v5 = v4.toByteArray();
            //输出验证码图片  好像c22a1175开头不需要验证码
            File cpFile = new File(gsWorkPath + "AuthCode.png");
            FileOutputStream out = new FileOutputStream(cpFile);
            out.write(v5);
            out.flush();
            out.close();
            //System.out.println("验证码储存位置："+cpFile.getAbsolutePath());
            String v1 = new String(v5);
            // System.out.println(v1);
            int v6 = v1.length();
            if(v6 < 26) {
                throw new Exception("获取验证码失败,请重新尝试");
            }
            String ssid = "";
            if("0123456789".equals(v1.substring(v6 - 10, v6))) {
                ssid = v1.substring(v6 - 26, v6 - 10);
System.out.println("ssid："+ssid);
            }
            return ssid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public byte[] MixAccountToBuffer(String mixAccount, String userID) {     // "11641250,fd4474de357019af2"
        byte gpLocal_1[];
        gpLocal_1 = new byte[12];
        String[] params = mixAccount.split(",");
        if (params.length > 1){
            MAPI.DWORD_BUFF8(MAPI.STRING_DEC32(params[0]), 0, gpLocal_1);
            SubUtils sysUtils = new SubUtils();
            sysUtils.fromAsciiStringToHex(params[1] + "0", 8, 4, gpLocal_1);
//MBAPP.MLOG("MixAccountToBuffer "+ mixAccount + " "+gpLocal_1);
        }
        return gpLocal_1;
    }
    @Override
    public String Base64MixAccount(String base64) {
        if (base64 != null && !"".equals(base64)) {
            String gsLocal_1;
            byte gpLocal_1[];
            SubUtils sysUtils = new SubUtils();
            try {
                gpLocal_1 = CodeBase64.decode(base64.getBytes());
                if (gpLocal_1.length >= 12) {
                    gsLocal_1 = sysUtils.fromHexStringAscii(8, 4, gpLocal_1);
//MBAPP.MLOG("Base64MixAccount "+ gsLocal_1);
                    gsLocal_1 = gsLocal_1.substring(0, gsLocal_1.length() - 1);
                    return String.format("%d,%s", MAPI.BUFF8_DWORD(0, gpLocal_1), gsLocal_1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MLOGE("KgChangBa Base64MixAccount error "+base64);
        return "";
    }
}
